from django import forms
from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
from django.db.models import Q
from types import FunctionType

from web.utils.response import BaseResponse
from web import models
from web.utils.bootstrap import BootstrapForm
from web.utils.pager import Pagernation
from web.utils.widgets import ColorRadioSelect
from web.utils.link import filter_reverse
from web.utils.group import Option, SearchGroupRow, get_search_group_condition


class DeviceModelForm(BootstrapForm, forms.ModelForm):
    exclude_field_list = ['color']

    class Meta:
        model = models.Device
        exclude = ['active']
        widgets = {
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }


def device_list(request):
    model_class = models.Device

    search_group = [
        Option('device_type'),
        Option('vendor')
    ]
    search_group_list = []
    for option_object in search_group:
        search_group_list.append(option_object.get_queryset_or_tuple(request, model_class))
    conn = get_search_group_condition(search_group, request)

    # 获取关键字搜索条件
    search_list = [
        'title__contains',
        'url__contains'
    ]
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    if keyword:
        con.connector = "OR"
        for item in search_list:
            con.children.append((item, keyword))

    queryset = models.Device.objects.filter(con).filter(**conn).filter(active=1)

    # # 1.处理表头
    # header_list = []
    # if list_display:
    #     for key_or_func in list_display:
    #         if isinstance(key_or_func, FunctionType):
    #             header_list.append(key_or_func(None, True))
    #         else:
    #             verbose_name = model_class._meta.get_field(key_or_func).verbose_name
    #             header_list.append(verbose_name)
    # else:
    #     header_list.append(model_class._meta.model_name)
    # # 2.处理表格内容
    # data_list = queryset[pager.start:pager.end]
    # body_list = []
    # for row in data_list:
    #     tr_list = []
    #     if list_display:
    #         for key_or_func in list_display:
    #             if isinstance(key_or_func, FunctionType):
    #                 tr_list.append(key_or_func(row, False))
    #             else:
    #                 tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
    #     else:
    #         tr_list.append(row)
    #     body_list.append(tr_list)

    pager = Pagernation(request, queryset)
    context = {
        'pager': pager,
        'keyword': keyword,
        'search_group_row_list': search_group_list
    }
    return render(request, 'device_list.html', context)


def device_add(request):
    if request.method == 'GET':
        form = DeviceModelForm()
        return render(request, 'form.html', {'form': form})

    form = DeviceModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()
    return redirect(filter_reverse(request, "/device/list/"))


def device_edit(request, pk):
    obj = models.Device.objects.filter(id=pk, active=1).first()
    if request.method == 'GET':
        form = DeviceModelForm(instance=obj)
        return render(request, 'form.html', {'form': form})
    form = DeviceModelForm(data=request.POST, instance=obj)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(reverse('device_list'))


def device_delete(request):
    cid = request.GET.get('cid', 0)
    if not cid:
        res = BaseResponse(status=False, detail='请选择要删除的数据')
        return JsonResponse(res.dict)

    exists = models.Device.objects.filter(id=cid, active=1).exists()
    if not exists:
        res = BaseResponse(status=False, detail="要删除的数据不存在")
        return JsonResponse(res.dict)
    models.Device.objects.filter(id=cid, active=1).update(active=0)
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)
